package com.bianmaba.spring.security.basic.handler;

import com.bianmaba.spring.security.util.ResponseUtil;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.security.web.authentication.logout.SimpleUrlLogoutSuccessHandler;
import org.springframework.security.web.session.SessionInformationExpiredEvent;
import org.springframework.security.web.session.SessionInformationExpiredStrategy;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@ConditionalOnMissingBean({BianmabaLogoutSuccessHandler.class})
public class BianmabaLogoutSuccessHandler extends SimpleUrlLogoutSuccessHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(BianmabaLogoutSuccessHandler.class);

    public BianmabaLogoutSuccessHandler() {
    }

    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response,
                                Authentication authentication) throws IOException, ServletException {
        String requestType = request.getHeader("request_type");
        if ("ajax".equals(requestType)) {
            UserDetails principal = (UserDetails) authentication.getPrincipal();
            Map<String, Object> result = new HashMap<String, Object>(0);
            result.put("success", true);
            result.put("SecurityMessage", true);
            result.put("result", "用户注销成功");
            result.put("data", principal);
            ResponseUtil.writeJson(response, result, 200);
            LOGGER.debug(result.get("result").toString());
        } else {
            super.onLogoutSuccess(request, response, authentication);
        }
    }

}
